﻿using EFDBModels;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;

namespace EFNetCoreAPI
{
    public class OracleDBContext : DbContext
    {
        public OracleDBContext(DbContextOptions<OracleDBContext> options)
               : base(options)
        {

        }

        //该处定义你要映射到数据库中的表
        //格式固定
        //public DbSet<Patient> Patient { get; set; }
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            //判断当前数据库是Oracle 需要手动添加Schema(DBA提供的数据库账号名称)
            if (this.Database.IsOracle())
            {
                modelBuilder.HasDefaultSchema("TESTDB");
            }
            DynamicDbSet(modelBuilder);
            base.OnModelCreating(modelBuilder);
        }
        /// <summary>
        /// 动态dbSet
        /// </summary>
        /// <param name="modelBuilder"></param>
        private static void DynamicDbSet(ModelBuilder modelBuilder)
        {
            foreach (var entityType in EntityType())
            {
                modelBuilder.Model.AddEntityType(entityType);
            }
        }

        /// <summary>
        /// 派生IEntity的实体
        /// </summary>
        /// <returns></returns>
        private static List<Type> EntityType()
        {
           return Context.GteTypes();
            Func<System.Attribute[], bool> IsAtt1 = o =>
            {
                foreach (System.Attribute a in o)
                {
                    if (a is TableAttribute)
                        return true;
                }
                return false;
            };
            var tplist = System.Reflection.Assembly.Load("EFDBModels").GetTypes().Where(o => o.IsClass && !o.IsAbstract && !o.IsGenericType && IsAtt1(Attribute.GetCustomAttributes(o, true)))
                  .Select(s => s).ToList();
            return tplist;
        }
    }
}
